import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.append(project_root)

# 初始化SQLAlchemy
db = SQLAlchemy()


def create_app():
    """应用工厂函数"""
    app = Flask(__name__)

    # 加载配置
    db_path = os.path.join(os.path.dirname(__file__), "instance", "app.db")
    app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///{db_path}"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False  # 禁用跟踪修改，提升性能

    # 初始化扩展
    db.init_app(app)

    # 注册蓝图
    from app.api import register_blueprints

    register_blueprints(app)

    # 创建数据库表
    with app.app_context():
        db.create_all()

    return app


if __name__ == "__main__":
    app = create_app()
    app.run(host="0.0.0.0", port=5000, debug=True)
